package com.sf;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sf.entity.SFPushStatus;
import org.apache.commons.collections4.CollectionUtils;

import java.io.FileInputStream;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

public class PushSFStatusData {

    /**
     * select
     *   pressure_sensor_id sensorNo,
     *   license_plate carrierNo,
     *   receipt_Time upTime,
     *   gmt_Create initDate,
     *   is_receive_data_timeout sensorStatus
     * from
     *   device_tyre_pressure_last
     * WHERE license_plate in  (select license_plate FROM `sf_license_plate_config`)
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

        //家里
     //   String excelPath ="C:\\Users\\86186\\Desktop\\车头测试.xlsx";
      //  String licensePath ="D:\\system\\demo\\dache-test\\service-hi\\src\\main\\resources\\";
        //公司
        String excelPath ="C:\\Users\\hcf\\Desktop\\挂车-0722.xlsx";
        String licensePath ="C:\\Users\\hcf\\IdeaProjects\\dache-test\\service-hi\\src\\main\\resources\\";

        // 创建一个输入流，将 Excel 文件读取出来
        InputStream inputStream = new FileInputStream(excelPath);
        Integer sensorType;
        String errorMsg ="";
        if (excelPath.contains("挂")) {
            licensePath =licensePath + "licensePlates.txt";
            errorMsg ="挂车";
            sensorType=1;
        } else {

            errorMsg ="车头";
            licensePath =licensePath + "licensePlatesHead.txt";
            sensorType = 2;
        }


        List<SFPushStatus> tmpList = EasyExcel.read(inputStream)
                // 设置与Excel表映射的类
                .head(SFPushStatus.class)
                // 设置sheet,默认读取第一个
                .sheet()
                // 设置标题所在行数
                .headRowNumber(1)
                // 异步读取
                .doReadSync();

        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


        HashSet<String> licenses = new HashSet<>();



        Set<String> fileLicensePlates = LicensePlates.getLicensePlates( licensePath);




        // 按carrierNo字段分组，并将分组结果转换为列表
        List<List<SFPushStatus>> groupedList = tmpList.stream()
                .collect(Collectors.groupingBy(SFPushStatus::getCarrierNo))
                .values()
                .stream()
                .map(group -> group.stream()
                        .map(status -> {
                            // 将initDate转换为LocalDate对象
                            LocalDate initDate;
                            // 将upTime转换为时间戳
                            LocalDateTime upTime ;
                            if (StrUtil.isBlank(status.getInitDate())) {
                                LocalDateTime randomDateTime = getRandomDateTime(null);
                                upTime = randomDateTime;
                                initDate = randomDateTime.toLocalDate();
                            }else {
                                initDate = LocalDate.parse(status.getInitDate(), dateTimeFormatter);
                                upTime = LocalDateTime.parse(status.getUpTime(), dateTimeFormatter);
                            }
                            long timestamp = upTime.toInstant(ZoneOffset.UTC).toEpochMilli() / 1000;
                            licenses.add(StrUtil.trim(status.getCarrierNo()));
                            return new SFPushStatus(StrUtil.trim(status.getSensorNo()), StrUtil.trim(status.getCarrierNo()), String.valueOf(timestamp), initDate.format(dateFormatter),status.getSensorStatus() == 0?1:0,sensorType);
                        })
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());



        Collection<String> subtractList = CollectionUtils.disjunction(licenses, fileLicensePlates);
        System.out.println(errorMsg +"补集: "+"\""+ StrUtil.join("\",\"",subtractList)+ "\"");
        for (String s : subtractList) {
            System.out.println(s);
        }

        List<List<List<SFPushStatus>>> partition = Lists.partition(groupedList, 100);
        for (List<List<SFPushStatus>> lists : partition) {
            Date now = new Date();
            long timestamp = now.getTime();
            //test
//        String appSecret = "1pJkS09dNn6tt";
//        String url ="https://gis-rss-scm-stsoc.sit.sf-express.com:48020/stsoc";

            //pro
            String appSecret = "opW79kLM78Sp";
            String url ="https://gis-rss-scm-stsoc.sf-express.com/stsoc";
            Map<String, Object> paramsHeader = Maps.newHashMap();
            paramsHeader.put("appid", "DCDZ");
            paramsHeader.put("timestamp",timestamp+"");
            String sign = Md5SignUtil.signRequest(paramsHeader,appSecret);
            paramsHeader.put("sign",sign);

            String res = OkHttpClient.syncPostHeader(url+"/openapi/pushStatus",paramsHeader, JSONObject.toJSONString(lists));
                System.out.println(res);

        }



    }


    public static LocalDateTime getRandomDateTime(LocalDateTime upTime) {
        if (upTime == null) {
            Random random = new Random();
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            // 获取昨天的开始和结束时间
            LocalDateTime startYesterday = now.minusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
            LocalDateTime endYesterday = now.minusDays(1).withHour(23).withMinute(59).withSecond(59).withNano(999999999);
            // 获取前天的开始和结束时间
            LocalDateTime startDayBeforeYesterday = now.minusDays(2).withHour(0).withMinute(0).withSecond(0).withNano(0);
            LocalDateTime endDayBeforeYesterday = now.minusDays(2).withHour(23).withMinute(59).withSecond(59).withNano(999999999);

            // 计算时间范围内的随机秒数
            long randomSeconds;
            if (random.nextBoolean()) {
                long startEpoch = startYesterday.atZone(ZoneId.systemDefault()).toEpochSecond();
                long endEpoch = endYesterday.atZone(ZoneId.systemDefault()).toEpochSecond();
                randomSeconds = startEpoch + (long) (random.nextDouble() * (endEpoch - startEpoch));
            } else {
                long startEpoch = startDayBeforeYesterday.atZone(ZoneId.systemDefault()).toEpochSecond();
                long endEpoch = endDayBeforeYesterday.atZone(ZoneId.systemDefault()).toEpochSecond();
                randomSeconds = startEpoch + (long) (random.nextDouble() * (endEpoch - startEpoch));
            }

            return LocalDateTime.ofEpochSecond(randomSeconds, 0, ZoneId.systemDefault().getRules().getOffset(now));
        }
        return upTime;
    }




}
